package com.test.mylotterysystem.comment.config;

import com.test.mylotterysystem.constants.Constants;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    /**
     * 普通队列
     * @return
     */
    @Bean(Constants.QUEUE_NAME)
    public Queue directQueue() {
        return QueueBuilder.durable(Constants.QUEUE_NAME).build();
    }


    // 创建交换机
    @Bean(Constants.EXCHANGE_NAME)
    public DirectExchange directExchange() {
        return ExchangeBuilder.directExchange(Constants.EXCHANGE_NAME).durable(true).build();
    }


    // 创建绑定关系
    @Bean(Constants.KEY)
    public Binding directQueueBinding(@Qualifier(Constants.QUEUE_NAME) Queue queue, @Qualifier(Constants.EXCHANGE_NAME) DirectExchange directExchange) {
        return BindingBuilder.bind(queue).to(directExchange).with(Constants.KEY);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, Jackson2JsonMessageConverter jsonMessageConverter) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter);
        return rabbitTemplate;
    }

    // 为了让存储到rabbitMQ中的数据可被读
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}
